# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Andrew Sun <adsun701@gmail.com>

_realname=c-ares
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.16.1
pkgrel=1
pkgdesc="C library that performs DNS requests and name resolves asynchronously (mingw-w64)"
arch=('any')
url="https://c-ares.haxx.se/"
license=("MIT, BSD")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc" 
"${MINGW_PACKAGE_PREFIX}-pkg-config" "${MINGW_PACKAGE_PREFIX}-cmake")
options=('strip' 'staticlibs')
source=(#"https://c-ares.haxx.se/download/${_realname}-${pkgver}.tar.gz"{,.asc}
        https://github.com/c-ares/c-ares/archive/cares-${pkgver//./_}.tar.gz
        0001-Use-RPM-compiler-options.patch
        0002-Add-static-pkg-config.patch
        0003-fix-cmake-targets.patch)
validpgpkeys=('914C533DF9B2ADA2204F586D78E11C6B279D5C91'
              '27EDEAF22F3ABCEB50DB9A125CC908FDB71E12C2')
sha256sums=('870962cc8f6b352303c404ce848e2ea1f1072f3c0a940042209a72179511c08c'
            'f00faa8723fd530b027f96b987ef19138628a49afdf52ffb0554b36156fc9d74'
            'dabb0e3e305b79bce5230088035e200ceaa0d88a78956aa2e2e2e6aa671ec86e'
            '766ea64dfd37df80441eeaddd9c1012c2a4a0391d8e9274cdd786f7af0620fb8')

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying $_patch"
    patch -Nbp1 -i "${srcdir}/$_patch"
  done
}

del_file_exists() {
  for _fname in "$@"
  do
    if [ -f $_fname ]; then
      rm -rf $_fname
    fi
  done
}
# =========================================== #

prepare() {
  cd "${srcdir}"/${_realname}-cares-${pkgver//./_}
  del_file_exists libcares-static.pc.in
  apply_patch_with_msg 0001-Use-RPM-compiler-options.patch \
    0002-Add-static-pkg-config.patch \
    0003-fix-cmake-targets.patch

  autoreconf -fi
}

build() {
  [[ -d "${srcdir}"/build-${CARCH} ]] && rm -rf "${srcdir}"/build-${CARCH}
  mkdir -p "${srcdir}"/build-${CARCH} && cd "${srcdir}"/build-${CARCH}
  
  ../${_realname}-cares-${pkgver//./_}/configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --enable-shared \
    --enable-static

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
      -Wno-dev \
      -G"MSYS Makefiles" \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      -DCMAKE_BUILD_TYPE="Release" \
      -DCARES_STATIC=ON \
      -DCARES_SHARED=ON \
      ../${_realname}-cares-${pkgver//./_}
}

package() {
  cd "${srcdir}"/build-${CARCH}
  make DESTDIR="${pkgdir}" install

  # msys2-runtime-devel provide nameser.h but mingw-w64 don't have it
  cp ${srcdir}/${_realname}-cares-${pkgver//./_}/nameser.h ${pkgdir}${MINGW_PREFIX}/include
  
  # provide pkgconfig files
  sed -i -e "s|Version: -|Version: ${pkgver}|g" libcares.pc libcares-static.pc
  install -Dm644 libcares.pc ${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/libcares.pc
  install -Dm644 libcares-static.pc ${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/libcares-static.pc
}
